let ws = null
function startWs(sid){
    console.log('开始ws...');
    // sid = new Date().getTime()+"_"+sid;
    ws = new WebSocket('ws://localhost:8765/crawler?sid='+sid);
    ws.onopen = function(e){
        console.log("连接服务器成功");
        sendWsMessage('system','client connect success,ws='+ws.toString());
        // ws.send("客户端ws连接成功");
    }
    ws.onclose = function(e){
        console.log("ws服务器关闭");
        console.error(e);
        startWs();
    }
    ws.onerror = function(e){
        console.log("ws连接出错");
        console.error(e);
        startWs();
    }

    ws.onmessage = function(message){
        let res = JSON.parse(message.data);
        // if(res.webContentsId == webContentsId){
        // }
        let msg = res.message ? JSON.stringify(res.message) : '';

        if(res.type == 'log'){
            appendLog(msg);
        }else if(res.type == 'stat'){  //统计
            document.getElementById('statBlock').value = msg;
        }else if(res.type == 'collectStatus'){  //开启或关闭
            // debugger;
            collectStart = JSON.parse(msg);
            changeButtonText('start',collectStart);
        }else{
            console.log(msg);
        }
    }

    function appendLog(message){
        // if(message.indexOf('crawler cmd execute done') > 0){
        //     crawler_state = false;
        //     alert('采集已结束')
        // }else if (message.indexOf('export cmd execute done') > 0){
        //     export_state = false;
        // }
        let text = '';
        let textareaObj = document.getElementById('txtLog');
        text = textareaObj.value;
        if(text.length > 10000){
            text = '';
        }
        text += "\n"+message;
        textareaObj.value = text;

        textareaObj.scroll({ top: textareaObj.scrollHeight, left: 0, behavior: "smooth" });

    }
}

let webviewShow = true;
let collectStart = true;
let webContentsId = '';
function componentInit(){
    const btnShowOrHideWebview = document.getElementById('btnShowOrHideWebview')
    btnShowOrHideWebview.addEventListener('click', () => {
        webviewShow = !webviewShow;
        changeButtonText('webview',webviewShow);
        sendWsMessage('showOrHideWebview',{value:webviewShow});

    });

    const btnStartOrStop = document.getElementById('btnStartOrStop')
    btnStartOrStop.addEventListener('click', () => {
        collectStart = !collectStart;
        startOrStopAction(collectStart);

    });
}

function changeButtonText(type,status){
    if(type == 'start'){
        if(status){
            document.getElementById('btnStartOrStop').innerText = '暂停';
        }else{
            document.getElementById('btnStartOrStop').innerText = '继续';

        }
    }else if(type == 'webview'){
        if(status){
            document.getElementById('btnShowOrHideWebview').innerText = '隐藏网页';
        }else{
            document.getElementById('btnShowOrHideWebview').innerText = '显示网页';

        }
    }
}

function startOrStopAction(collectStart){
    changeButtonText('start',collectStart);
    sendWsMessage('collectStatus',{collectStart:collectStart});
}


function getUrlParam(key){
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(key);
}

function init(){
    webContentsId = getUrlParam('webContentsId');
    startWs(webContentsId);
    componentInit();
}

function sendWsMessage(type,message){
    let data = JSON.stringify({type:type,message:message})
    ws.send(data);

}



window.onload = function(e){


    init();

    // setTimeout(function(){
    //
    // },3000)

    setInterval(function(){
        sendWsMessage('ping','');
    },30000)

};
